<template>
  <el-container style="height: 100vh;">
    <el-header ref="header"
      style="height: 5%; background-color: #FAECD7; display: flex; justify-content: space-between; align-items: center; padding: 0 10px;">
      <el-link @click="goToHome" style="margin-left: 5px;" :underline="false"
        :style="{ fontSize: linkFontSize + 'px' }">{{ '< 个人信息' }}</el-link>
          <img :src="imageicon" class="imageicon" alt="icon" style="margin-right: 5px;" />
    </el-header>

    <el-main style="height: 95%; background-color: #F6F4EF; padding: 0px;">
      <el-row style="height: 100%;">
        <el-col :span="3"></el-col>
        <el-divider direction="vertical" style="height: 95%; margin:0px; border-width:2px; border-color:#DEDCD9" />
        <!--此处开始为下方内容-->
        <el-col :span="18" style="">
          <el-image class="imageheader" :src="imageheader" fit="cover" />
          <div style="display: flex; align-items: flex-start;margin-left: 20px;">
            <!-- 头像 -->
            <el-avatar :size="90" :src="imageavatar" style="margin-right: 10px;" />
            <!-- 内容区域，包含按钮和ID -->
            <div style="display: flex; flex-direction: column; justify-content: space-between;">
              <!-- ID -->
              <div style="margin-top: 20px;">ID: {{ ID }}</div>
              <!-- 更换头像按钮 -->
              <el-button plain size="small" @click="triggerFileInput" style="margin-top: 20px;">更换头像</el-button>
            </div>
          </div>
          <input type="file" ref="fileInput" style="display: none" @change="handleFileChange" />
          <el-form label-width="auto" label-position="left" style="margin-left: 48px; margin-top: 30px;">

            <el-row><el-form-item label="用户名：" class="inputbox">
                <el-input placeholder="用户名" v-model="form.username" disabled/>
              </el-form-item></el-row>

            <el-row><el-form-item label="邮箱：" class="inputbox">
                <el-input placeholder="邮箱" v-model="form.email" disabled/>
              </el-form-item></el-row>

            <el-row><el-form-item label="手机号：" class="inputbox">
                <el-input placeholder="手机号" v-model="form.phone" disabled/>
              </el-form-item></el-row>

            <el-row><el-form-item label="偏好设置:">
                <el-checkbox-group v-model="form.type">
                  <el-checkbox value="checkbox_1">
                    浅色
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item></el-row>

            <el-form-item style="position: relative; top: 50px;">
              <el-button color="#F4CE98" type="primary" plain>
                <span style="color:#F4CE98;" @click="dialogFormVisible = true">修改信息</span></el-button>
              <el-button plain @click="logOut" style="margin-left: 20px;">退出登录</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-divider direction="vertical" style="height: 95%; margin:0px; border-width:2px; border-color:#DEDCD9" />
      </el-row>
      <!--修改表单-->
      <el-dialog v-model="dialogFormVisible" title="修改个人信息" width="450" style="background-color:#F6F4EF;">
        <el-form :model="changeFrom" :rules="rules" ref="changeFormRef" style="margin-top: 50px;" label-width="auto"
          label-position="left">
          <el-form-item label="新用户名" prop="name">
            <el-input v-model="changeFrom.name" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="新手机号" prop="phone">
            <el-input v-model="changeFrom.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="changeFrom.email" placeholder="请输入邮箱" disabled></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="verifyCode">
            <el-input v-model="changeFrom.verifyCode" placeholder="请输入验证码">
              <template #append>
                <el-button :style="{ backgroundColor: isSending || countdown > 0 ? '#ccc' : '#F4CE98', color: 'white' }"
                  @click="sendVerifyCode" :disabled="isSending || countdown > 0">
                  {{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="password">
            <el-input type="password" v-model="changeFrom.password" placeholder="请输入密码"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">关 闭</el-button>
            <el-button type="primary" @click="submitForm" style="background-color: #F4CE98; border: none;">
              提 交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>


<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { nextTick } from 'vue';
import image1 from "@/assets/header_01.png";
import image2 from '@/assets/header_02.png';
import { ElMessage } from 'element-plus';
import { md5 } from 'js-md5';
// State variables
const ID = ref(114514);
const imageicon = ref(image1);
const imageheader = ref(image2);
const imageavatar = ref(image1);
const fileInput = ref(null);
const header = ref(null); // Reference to the header element
const linkFontSize = ref(0); // Font size for the link
const dialogFormVisible = ref(false);
const countdown = ref(0);
const verificationCode = ref(0);
const isSending = ref(false);

// Reactive form data
const form = reactive({
  username: '',
  phone: '',
  email: '',
  type: [],
});

const changeFrom = ref({
  name: '',
  phone: '',
  email: '',
  verifyCode: '',
  password: ''
});

const rules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机', trigger: 'blur' },
    { type: 'phone', message: '邮箱格式不正确', trigger: 'blur' }
  ]
};

// Router instance
const router = useRouter();

// Methods
const triggerFileInput = () => {
  fileInput.value.click();
};

const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    const url = URL.createObjectURL(file);
    imageavatar.value = url;
    fetch()
  }
};

const logOut = () => {
  // 退出登录相关操作
  localStorage.removeItem('tokenName');
  localStorage.removeItem('tokenValue');
  fetch('http://localhost:8080/api/user/logout', {
    method: 'GET',
    credentials: 'include',
    headers: {
      'Accept': 'application/json',
    }
  }).then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`)
    }
    return response.json()
  }).then(data => {
    console.log(data)
  }).catch(error => console.error('Error: ', error));
  ElMessage({
    message: '退出登录成功',
    type: 'success'
  })
  goToLogin();
};

const submitForm = async () => {
  if (verificationCode.value != changeFrom.value.verifyCode) {
    ElMessage.error('验证码错误')
    return;
  }
  fetch('http://localhost:8080/api/user/update', {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username: changeFrom.value.name,
      password: md5(changeFrom.value.password),
      phone: changeFrom.value.phone
    })
  }).then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`)
    }
    return response.json()
  }).then(data => {
    if (data['code'] != 200) {
      ElNotification({
        title: 'Error',
        message: data['msg'],
        type: 'error',
      })
    }
    else if (data['code'] == 200) {
      ElMessage({
        message: '修改信息成功',
        type: 'success'
      })
      dialogFormVisible.value = false;
      getUserInfo()
    }
  }).catch(error => console.error('Error: ', error));
};

const goToLogin = () => {
  if (router) {
    router.push('/login');
  } else {
    console.error("Router is undefined");
  }
};

const goToHome = () => {
  if (router) {
    router.push('/home');
  } else {
    console.error("Router is undefined");
  }
};

// This function calculates the font size based on the header height
const calculateFontSize = () => {
  if (header.value) {
    const headerHeight = header.value.$el.offsetHeight; // Get the height of the header
    linkFontSize.value = headerHeight / 3; // Set font size to half of the header height
  }
};
// Ensure the font size is calculated when the component is mounted
onMounted(async () => {
  await nextTick(); // 等待 DOM 渲染完成
  calculateFontSize(); // 调用计算字体大小的方法
  window.addEventListener('resize', calculateFontSize); // 窗口大小变化时重新计算
});

const sendVerifyCode = async () => {
  if (isSending.value || countdown.value > 0 || changeFrom.value.email == '') return;
  isSending.value = true;
  let url = 'http://localhost:8080/api/user/sendLoginEmailVerificationCode?email=';
  url += changeFrom.value.email;
  // 发送验证码
  fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'text/plain',
      'Accept': 'application/json',
    },
    body: changeFrom.value.email
  }).then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  }).then(data => {
    let status = data['code'];
    if (status == 200) {
      verificationCode.value = data['msg'];
      console.log(data['msg']);
    }
  }).catch(error => console.error('Error:', error));

  console.log('验证码发送成功');

  countdown.value = 60; // 设置倒计时时间为60秒
  const timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
      isSending.value = false; // 允许再次发送验证码
      console.log('倒计时结束，按钮恢复');
    }
  }, 1000); // 设置定时器每1000毫秒调用一次
};

const getUserInfo = () => {
  fetch('http://localhost:8080/api/user/getUser', {
    method: 'GET',
    credentials: 'include',
    headers: {
      'Accept': 'application/json',
    }
  }).then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`)
    }
    return response.json()
  }).then(data => {
    ID.value = data['userId']
    form.username = data['username']
    form.phone = data['phone']
    form.email = data['email']
    changeFrom.value.name = data['username']
    changeFrom.value.phone = data['phone']
    changeFrom.value.email = data['email']
    imageavatar.value = data['avatar']
  })
}
getUserInfo()
</script>


<style scoped>
.inputbox {
  width: 460px;
}

.imageicon {
  height: 100%;
  object-fit: contain;
}

.imageheader {
  width: 100%;
  height: 120px;
  opacity: 0.19;
}

.el-link {
  transition: font-size 0s ease-in-out;
}

.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
</style>
